package com.imist.sm.global;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//这里可以继承HttpServlet或者GenericServlet（抽象类）
public class DispatcherServlet extends GenericServlet {
    private ApplicationContext context ;

    /**
     * 该方法只会在初始化的时候调用一次，以后每次请求不再调用
     * @throws ServletException
     */
    @Override
    public void init() throws ServletException {
        super.init();
        context = new ClassPathXmlApplicationContext("spring.xml");
    }

    /**
     *  一层路径直接调用selfController，二层路径解析出对应的bean然后调用下面的方法
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /**
         * /staff/add.do      /login.do
         * staffController
         *
         * public void add(HttpServletRequest request , HttpServletResponse){}
         */

        String path = request.getServletPath().substring(1);//去掉 `/`
        String beanName = null;
        String methodName = null;
        int index = path.indexOf('/');

        if (index != -1){
            beanName = path.substring(0,index)+"Controller";
            methodName = path.substring(index +1 ,path.indexOf(".do"));
        }else {
            beanName = "selfController";
            methodName = path.substring(0,path.indexOf(".do"));
        }
        Object obj = context.getBean(beanName);
        try {
            Method method = obj.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(obj,request,response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
